<template>
    <div class="trendCanBeStored">
        <div class="loading-box" v-show="show">
            loading……
        </div>
        <!-- <div class="header-box">
            <div class="dialog-title">
               
                Tags Trend
            </div>
        </div>
        -->
        <div class="content-box">
            <div id="main" class="trendArea">

            </div>
            <div class="top-box">
                <div>
                    <span>Start:</span>
                    <el-date-picker v-model="form.startTime" type="datetime" placeholder="Please enter"
                        :disabled-date="disabledStartDate" :disabled="form.endTime && form.startTime > form.endTime"
                        @change="changeStartTime"></el-date-picker>
                    <span>End:</span>
                    <el-date-picker v-model="form.endTime" type="datetime" placeholder="Please enter"
                        :disabled="form.startTime && form.endTime < form.startTime"
                        @change="changeEndTime"></el-date-picker>
                </div>
                <div class="ml-1">
                    <el-button type="primary" v-if="!isEdit" @click="isEdit = !isEdit">edit</el-button>
                    <el-button type="primary" v-if="isEdit" @click="addFun">add</el-button>
                    <el-button type="primary" v-if="isEdit" @click="saveFun">save</el-button>
                </div>
            </div>
            <el-table :data="storedConfigsData" style="width: 100%" border height="230">
                <el-table-column label="Color" align="center" width="130">
                    <template #default="scope">
                        <div style="display: flex; justify-content: center; align-items: center; height: 100%;">
                            <div v-if="!isEdit"
                                :style="{ background: scope.row.color, width: '60px', height: '20px', border: scope.row.color == '#ffffff' ? '1px solid #909399' : 'none' }">
                            </div>
                            <el-color-picker v-if="isEdit" v-model="scope.row.color"></el-color-picker>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="trendName" label="Trend Name" align="center">
                    <template #default="scope">
                        <div v-if="!isEdit">{{ scope.row.trendName }}</div>
                        <div v-if="isEdit"><el-input v-model="scope.row.trendName"
                                placeholder="Please enter the content"></el-input>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="tagName" label="Tag Name" align="center">
                    <template #default="scope">
                        <div v-if="!isEdit">{{ scope.row.tagName }}</div>
                        <!-- productionid -->
                        <div v-if="isEdit">
                            <el-select v-model="scope.row.tagName" placeholder="Please select">
                                <el-option v-for="item in productionid" :key="item.tagName" :label="item.label"
                                    :value="item.tagName">
                                </el-option>
                            </el-select>
                        </div>

                    </template>
                </el-table-column>
                <el-table-column prop="axes" label="Axes" align="center" width="250" show-overflow-tooltip>
                    <template #default="scope">
                        <div v-if="!isEdit">{{ scope.row.axes }}</div>
                        <div v-if="isEdit">
                            <el-select v-model="scope.row.axes" placeholder="Please select">
                                <el-option v-for="item in axesoOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column v-if="isEdit" label="Review" align="center" width="100">
                    <template #default="scope">
                        <span style="color: red; cursor: pointer;" @click="confirmEvent(scope.row)">Delete</span>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>

</template>
<script>
import * as echarts from "echarts";
import { getTrendTimeValueByTagName, getWellInfoProductionLast, getConfigList, saveConfig } from '@/api/index'
import { ElLoading } from 'element-plus'
import { nextTick } from "vue";
export default {
    name: "TrendCanBeStored",
    data() {

        return {
            show: false,
            form: {
                startTime: localStorage.getItem('startTime') ? localStorage.getItem('startTime') : "",
                // endTime: this.convertBeijingToCalgary(new Date()),
                endTime: localStorage.getItem('endTime') ? localStorage.getItem('endTime') : this.convertBeijingToCalgary(new Date()),
                tagName: ""
            },
            tagName: "",
            xData: [],
            dateList: [],
            valueList: [],
            dataListArray: [],
            totalLegend: [],
            lineColor: [
                '#fe7501', '#00d4fa', '#f371ff', '#4ad400', '#bb1504', '#31adf3', '#0345e3',
                '#9ce6fd', '#868ecb', '#f90aaf', '#f9cdd8',
                '#fc7298', '#5a91f5', '#b6e959', '#4ec4d6',
                '#fed505', '#f59f83', '#a00386', '#5b63ff', '#b29bc3', '#7de7a2', '#fec503'],
            myChart: "",
            dialogTableVisible: false,
            tableData: [],
            sortedDates: [],
            seriesList: [],
            legendGroup: [[], [], [], []],
            deleteTagName: '',//标记要删除的tagName
            doubleY: false,
            loading: false,
            timer: null,
            storedConfigsData: [],
            isEdit: false,
            axesoOptions: [
                {
                    value: 'top left',
                    label: 'top left'
                },
                {
                    value: 'top right',
                    label: 'top right'
                },
                {
                    value: 'middle left',
                    label: 'middle left'
                },
                {
                    value: 'middle right',
                    label: 'middle right'
                },
                {
                    value: 'below left',
                    label: 'below left'
                },
                {
                    value: 'below right',
                    label: 'below right'
                },
            ],
            productionid: []
        }
    },
    created() {
        this.show = true;
        this.wellId()
        this.getConfigList()
        this.initTime();//初始化并存储起止时间



        document.title = 'Tags-Trend';
    },

    mounted() {

        window.addEventListener("resize", this.handleChartResize);
    },
    watch: {
        tagName: {
            handler(newVal, oldVal) {
                if (newVal && newVal.length > 0) {
                    // this.getTrendTimeValueByTagNameFun(this.form)
                }
            }, immediate: true
        }
    },
    beforeUnmount() {
        if (this.myChart) {
            this.myChart.dispose()
        }
    },
    methods: {
        addFun() {
            this.storedConfigsData.unshift({
                axes: '',
                color: '',
                trendName: '',
                tagName: '',
            })
        },
        //随机颜色生成
        getRandomHexColor() {
            // 生成更鲜艳的 #RRGGBB 格式随机颜色
            // 生成鲜艳明亮的 #RRGGBB 格式随机颜色
            const r = Math.floor(Math.random() * 128) + 128; // 红色分量 128-255
            const g = Math.floor(Math.random() * 128) + 128; // 绿色分量 128-255
            const b = Math.floor(Math.random() * 128) + 128; // 蓝色分量 128-255

            // 转换为十六进制
            const toHex = (value) => value.toString(16).padStart(2, '0');

            return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
        },
        hasAnyEmptyProperty(array, properties) {
            return array.some(obj =>
                properties.some(property =>
                    obj[property] === null ||
                    obj[property] === undefined ||
                    obj[property] === ""
                )
            );
        },
        saveFun() {
            if (!this.hasAnyEmptyProperty(this.storedConfigsData, ['axes', 'color', 'trendName', 'tagName'])) {
                this.isEdit = false
                this.saveConfig(this.storedConfigsData)
            }else{
                this.$message('Please check if any attributes are empty')
            }


        },
        //保存配置信息
        async saveConfig(data) {
            let res = await saveConfig(data)
            if (res.code == 200) {
                this.addAListToTheData(data)
            }
        },
        //给数据添加列表
        async addAListToTheData(data) {
            this.dataListArray = []
            const promises = data.map(item => {
                this.form.tagName = item.tagName
                return this.getTrendTimeValueByTagNameFun(this.form, item);
            });
            try {
                await Promise.all(promises);
                // 所有异步操作都完成后的回调
                const normalObject = JSON.parse(JSON.stringify(this.dataListArray));
                this.getLocationDataInitChart(normalObject)
            } catch (error) {
                console.error('An error occurred while fetching trends:', error);
            }
        },
        async wellId() {
            let formData = new FormData();
            formData.append("wellId", this.$route.query.wellId);
            getWellInfoProductionLast(formData).then(res => {
                if (res.code == 200) {
                    this.productionid = res.data.lastInfoList;
                }
            });
        },
        //获取列表信息
        async getConfigList() {
            let res = await getConfigList()
            if (res.code == 200) {
                console.log(res, '查询已存的数据列表');
                this.storedConfigsData = res.data
                const tagName = this.$route.query.key
                const hasTag = this.storedConfigsData.some(item => item.tagName === tagName);
                if (!hasTag) {
                    //当前数据里没有此条，要添加并且保存
                    this.storedConfigsData.push(
                        {
                            axes: 'top left',
                            color: this.getRandomHexColor(),
                            trendName: tagName,
                            tagName: tagName
                        }
                    )
                    this.saveConfig(this.storedConfigsData)
                } else {
                    //否则直接进行下一步请求渲染
                    this.addAListToTheData(this.storedConfigsData)
                }
            }
        },


        confirmEvent(row) {
            this.storedConfigsData.forEach((item, index) => {
                if (item.tagName === row.tagName) {
                    this.storedConfigsData.splice(index, 1)
                }
            })
        },
        //给每一条的数据添加数据列表
        async getTrendTimeValueByTagNameFun(params, data) {
            let res = await getTrendTimeValueByTagName(params)
            if (res.code !== 200) {
                this.show = false
                return this.$message.error(res.msg);
            } else {
                // 结果不为空对象
                if (JSON.stringify(res.data) === '{}') {
                    this.show = false;
                    return this.$message.warning("no data")
                } else {
                    this.dataListArray.push({
                        axes: data.axes,
                        color: data.color,
                        trendName: data.trendName,
                        tagName: data.tagName,
                        timeList: res.data.timeList,
                        valueList: res.data.valueList
                    })
                    this.xData = res.data.timeList
                    const normalObject = JSON.parse(JSON.stringify(this.dataListArray));
                    this.getLocationDataInitChart(normalObject)
                }

            }
        },
        getLocationDataInitChart(normalObject) {
            let dataList = normalObject//需要把这里改成实时查询
            let xData = this.xData
            let legendGroup = [[], [], [], []];
            let seriesList = [];


            dataList.forEach((item, i) => {
                if (item.axes === 'top left') {
                    legendGroup[0].push(item.tagName)
                    seriesList.push({
                        name: item.tagName,
                        type: 'line',
                        showSymbol: false,
                        data: item.valueList,
                        itemStyle: {
                            color: item.color
                        },
                        xAxisIndex: 0,
                        yAxisIndex: 0,
                        gridIndex: 0
                    })
                } else if (item.axes === 'top right') {

                    legendGroup[1].push(item.tagName)
                    seriesList.push({
                        name: item.tagName,
                        type: 'line',
                        showSymbol: false,
                        data: item.valueList,
                        itemStyle: {
                            color: item.color
                        },
                        xAxisIndex: 0,
                        yAxisIndex: 1,
                        gridIndex: 0
                    })
                } else if (item.axes === 'middle left') {
                    legendGroup[1].push(item.tagName)
                    seriesList.push({
                        name: item.tagName,
                        type: 'line',
                        showSymbol: false,
                        data: item.valueList,
                        itemStyle: {
                            color: item.color
                        },
                        xAxisIndex: 1,
                        yAxisIndex: 2,
                        gridIndex: 1
                    })
                } else if (item.axes === 'middle right') {
                    legendGroup[1].push(item.tagName)
                    seriesList.push({
                        name: item.tagName,
                        type: 'line',
                        showSymbol: false,
                        data: item.valueList,
                        itemStyle: {
                            color: item.color
                        },
                        xAxisIndex: 1,
                        yAxisIndex: 3,
                        gridIndex: 1
                    })
                }
                else if (item.axes === 'below left') {
                    legendGroup[1].push(item.tagName)
                    seriesList.push({
                        name: item.tagName,
                        type: 'line',
                        showSymbol: false,
                        data: item.valueList,
                        itemStyle: {
                            color: item.color
                        },
                        xAxisIndex: 2,
                        yAxisIndex: 4,
                        gridIndex: 2
                    })
                }
                else if (item.axes === 'below right') {
                    legendGroup[1].push(item.tagName)
                    seriesList.push({
                        name: item.tagName,
                        type: 'line',
                        showSymbol: false,
                        data: item.valueList,
                        itemStyle: {
                            color: item.color
                        },
                        xAxisIndex: 2,
                        yAxisIndex: 5,
                        gridIndex: 2
                    })
                } else {
                    legendGroup[0].push(item.tagName)
                    seriesList.push({
                        name: item.tagName,
                        type: 'line',
                        showSymbol: false,
                        data: item.valueList,
                        itemStyle: {
                            color: item.color
                        },
                        xAxisIndex: 0,
                        yAxisIndex: 0,
                        gridIndex: 0
                    })
                }
            })
            this.myChart = this.initEcharts(xData, seriesList, legendGroup)
        },
        handleChartResize() {
            if (!this.myChart) {
                return;
            }
            this.myChart.resize();
        },
        createGrid(top, height) {
            return {
                left: "60px",
                right: "60px",
                top: top,
                height: height
            };
        },
        getGridConfig(setChart) {
            const gridConfigs = {
                '0': [
                    this.createGrid("3%", "82%"),
                    this.createGrid("32%", "0%"),
                    this.createGrid("86%", "0%")
                ],
                '1': [
                    this.createGrid("3%", "0%"),
                    this.createGrid("3%", "82%"),
                    this.createGrid("86%", "0%")
                ],
                '2': [
                    this.createGrid("3%", "0%"),
                    this.createGrid("32%", "0%"),
                    this.createGrid("3%", "82%")
                ],
                '01': [
                    this.createGrid("3%", "39%"),
                    this.createGrid("45%", "39%"),
                    this.createGrid("86%", "0%")
                ],
                '12': [
                    this.createGrid("3%", "0%"),
                    this.createGrid("3%", "39%"),
                    this.createGrid("45%", "39%")
                ],
                '02': [
                    this.createGrid("3%", "39%"),
                    this.createGrid("32%", "0%"),
                    this.createGrid("45%", "39%")
                ],
                '012': [
                    this.createGrid("3%", "26%"),
                    this.createGrid("32%", "26%"),
                    this.createGrid("61%", "26%")
                ]
            };

            if (setChart.length === 1) {
                const element = setChart[0].toString();
                return gridConfigs[element] || [];
            } else if (setChart.length === 2) {
                const elements = setChart.sort().join('');
                return gridConfigs[elements] || [];
            } else if (setChart.length === 3) {
                return gridConfigs['012'] || [];
            }
            return [];
        },
        initEcharts(xData, seriesList, legendGroup) {
            var chartDom = document.getElementById('main');
            var myChart = echarts.init(chartDom);
            myChart.clear();
            var grid = []
            var option;
            console.log(seriesList, 7777777);
            let chart = []
            seriesList.forEach(v => {
                chart.push(v.gridIndex)
            })
            let setChart = [...new Set(chart)]
            grid = this.getGridConfig(setChart);

            option = {
                // legend: [
                //     {
                //         data: legendGroup[0],
                //         left: 'left',
                //         textStyle: {
                //             color: '#ffffff'
                //         }
                //     },
                //     {
                //         data: legendGroup[1],
                //         left: 'right',
                //         textStyle: {
                //             color: '#ffffff'
                //         }
                //     },
                //     {
                //         data: legendGroup[2],
                //         top: '50%',
                //         left: 'left',
                //         textStyle: {
                //             color: '#ffffff'
                //         }
                //     },
                //     {
                //         data: legendGroup[3],
                //         top: '50%',
                //         left: 'right',
                //         textStyle: {
                //             color: '#ffffff'
                //         }
                //     },
                // ],
                tooltip: {
                    trigger: 'axis',// 使用坐标轴触发，而不是数据项触发。这样可以显示所有系列的数据。

                    formatter: function (params) {
                        let str = '<div style="display:flex;align-items: flex-start;">' + params[0].name + '</div>';
                        str += ''
                        params.forEach((item) => {
                            if (item.seriesName !== "Warning") {
                                str += `<div style="display:flex;align-items: center;justify-content: space-between;"><div style="display:flex;align-items: center;justify-content: center;"><div style="width:0.5rem;height:.5rem;background:${item.color}; border-radius: 1rem;margin-top:0.1rem;margin-right:0.3rem"></div><span style="color:${item.color}">${item.seriesName}：</span></div><div><span style="color:${item.color};"><b>${item.data}</b></span> </div></div>`

                            }
                        })
                        return str;
                    }
                },
                xAxis: [
                    {
                        type: 'category',
                        data: xData,
                        gridIndex: 0,
                        show: false,

                    },

                    {
                        type: 'category',
                        data: xData,
                        gridIndex: 1,
                        show: false,
                    },
                    {
                        type: 'category',
                        data: xData,
                        gridIndex: 2,
                        show: true,
                    }

                ],

                yAxis: [
                    {
                        type: 'value',
                        position: 'left',
                        gridIndex: 0,
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: '#44485d',
                            },
                        },
                        // scale: true, //自适应
                    },
                    {
                        type: 'value',
                        position: 'right',
                        gridIndex: 0,
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: '#44485d',
                            },
                        },
                    },
                    {
                        type: 'value',
                        position: 'left',
                        gridIndex: 1,
                        top: '35%',
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: '#44485d',
                            },
                        },
                    },
                    {
                        type: 'value',
                        position: 'right',
                        gridIndex: 1,
                        top: '35%',
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: '#44485d',
                            },
                        },
                    },
                    {
                        type: 'value',
                        position: 'left',
                        gridIndex: 2,
                        top: '80%',
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: '#44485d',
                            },
                        },
                    },
                    {
                        type: 'value',
                        position: 'right',
                        gridIndex: 2,
                        top: '80%',
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: '#44485d',
                            },
                        },
                    },
                ],
                axisPointer: {
                    link: [
                        {
                            xAxisIndex: 'all'
                        }
                    ],
                    animation: false
                },
                grid: grid,
                series: seriesList,
                dataZoom: [
                    {
                        show: true,
                        realtime: true,
                        start: 0,
                        end: 100,
                        xAxisIndex: [0, 1, 2],
                        height: 12,
                        textStyle: {
                            color: "#fff"
                        },
                        showDataShadow: false,
                    },
                    {
                        type: 'inside',
                        realtime: true,
                        start: 0,
                        end: 100,
                        xAxisIndex: [0, 1, 2],
                        showDataShadow: false,
                    },
                    {
                        type: 'inside',
                        realtime: true,
                        start: 0,
                        end: 100,
                        xAxisIndex: [0, 1, 2],
                        showDataShadow: false,
                    },
                ],
            };

            option && myChart.setOption(option);
            // 监听窗口大小改变事件
            window.addEventListener('resize', function () {
                myChart.resize();
            });
            this.show = false;
            return myChart
        },
        // ----------------------------------------------
        initTime() {
            let endTime = "";
            if (this.isDateObject(this.form.endTime)) {
                endTime = this.formatDate(this.form.endTime);
            } else {
                endTime = this.form.endTime;
            }
            this.calculateTime(endTime, "day14", "0");
        },
        isDateObject(value) {
            return value instanceof Date;
        },
        formatDate(date) {
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, "0");
            const day = date
                .getDate()
                .toString()
                .padStart(2, "0");
            const hours = date
                .getHours()
                .toString()
                .padStart(2, "0");
            const minutes = date
                .getMinutes()
                .toString()
                .padStart(2, "0");
            const seconds = date
                .getSeconds()
                .toString()
                .padStart(2, "0");

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        calculateTime(timeString, unit, type) {
            const time = new Date(timeString);
            const step = {
                hour: 28800000, // 8小时
                day: 86400000, // 一天
                day7: 604800000, // 一天
                day14: 1209600000, // 一天
                day30: 2592000000, // 一天
                day60: 5184000000 // 一天
            };
            if (type == "0") {
                // 减 计算startTime
                const newTime = new Date(time.getTime() - step[unit]);
                this.form.startTime = this.formatDate(newTime);
                localStorage.setItem('startTime', this.formatDate(newTime))
            } else {
                // 加 计算endtime
                const newTime = new Date(time.getTime() + step[unit]);
                this.form.endTime = this.formatDate(newTime);
            }
        },
        // 将北京时间转换为卡尔加里时间
        convertBeijingToCalgary(beijingDate) {
            const options = {
                timeZone: 'America/Edmonton',  // 卡尔加里所属时区
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false                 // 强制24小时制
            };

            // 直接生成目标格式的字符串
            const formatter = new Intl.DateTimeFormat('en-CA', options);
            const calgaryTime = formatter.format(new Date())
                .replace(/(\d{4})-(\d{2})-(\d{2}),? (\d{2}:\d{2}:\d{2})/, '$1-$2-$3 $4');
            return calgaryTime
        },
        disabledStartDate(time) {
            if (this.form.endTime) {
                return time.getTime() > new Date(this.form.endTime).getTime();
            }
            return false;
        },
        changeStartTime(item) {
            const date = new Date(item);
            const year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            let hours = date.getHours();
            let minutes = date.getMinutes();
            let seconds = date.getSeconds();
            month = month < 10 ? '0' + month : month;
            day = day < 10 ? '0' + day : day;
            hours = hours < 10 ? '0' + hours : hours;
            minutes = minutes < 10 ? '0' + minutes : minutes;
            seconds = seconds < 10 ? '0' + seconds : seconds;
            this.form.startTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            localStorage.setItem('startTime', this.form.startTime)
            if (this.form.endTime && this.form.startTime > this.form.endTime) {
                this.form.startTime = this.form.endTime;
                localStorage.setItem('startTime', this.form.startTime)
            }
            this.addAListToTheData(this.storedConfigsData)
        },
        changeEndTime(value) {
            this.form.endTime = this.formatDate(value)
            if (this.form.startTime && this.form.endTime < this.form.startTime) {
                this.form.endTime = this.form.startTime;
            }
            localStorage.setItem('endTime', this.form.endTime)
            this.addAListToTheData(this.storedConfigsData)
        },
    }
}
</script>
<style scoped lang="scss">
.loading-box {
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    font-size: 1rem;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgb(0, 0, 0, 0.6);
    z-index: 100;
    color: #ffffff;
}

.custom-loading {
    z-index: 1500;
    /* 或者比你想要的 Dialog 的 z-index 低一些 */
}

.trendCanBeStored {
    width: 100vw;
    height: 100vh;

    .header-box {
        background: url("@/assets/header_bg.png") no-repeat;
        background-position: center center;
        height: 5h;
        font-size: 1.8rem;
        padding-top: 0.5rem;
        color: rgb(17, 137, 229);
    }

    .top-box {
        padding-top: 1vh;
        height: 4vh;
        display: flex;
        justify-content: space-between;
        margin-top: -20px;

        span {
            padding-left: 1vw;
            padding-right: 0.2vw;
            color: #eeeeee;
        }
    }

    .content-box {
        height: 94vh;
        padding: 10px;

        .dialog-content {

            //border: 1px solid #ff0000;
        }
    }

    .ml-1 {
        margin-left: 1vw;
    }

    .trendArea {
        width: 100%;
        height: 70vh;
    }
}
</style>